<?php

namespace app\common\service;

use app\admin\model\SystemUploadfile;
use EasyAdmin\upload\Uploadfile;
use think\Image;

class UploadService
{
    public static function checkAuth()
    {
        return true;
    }

    public static function upfile($filename = 'file', $uploadType = 'local', $is_water = false, $thumb = false)
    {
        if (!is_file($filename)) {
            $File = request()->file($filename);
        } else {
            $File = $filename;
        }
        $uploadConfig = sysconfig('upload');
        if (!$uploadType) {
            $uploadType = $uploadConfig['upload_type'];
        }
        $maxSize = $uploadConfig['upload_allow_size'] * 1024 * 1024;

        $rule = [
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$maxSize}",
        ];
//        $res=validate_ext(['file'=>$File], $rule);
//        if(isset($res['code'])&&$res['code']===0){
//            return $res;
//        }
        $hash = md5_file($File);
        $systemUploadfile = (new SystemUploadfile())->where('sha1', $hash)->find();

        $fileUrl = $fileExist = '';
        if ($systemUploadfile) {
            $fileUrl = $systemUploadfile->url;
            if ($systemUploadfile->upload_type == 'local') {
                $fileExist = is_file(ROOT_PATH . ('/public' . $fileUrl));
            } else {
                $fileExist = uri_valid($fileUrl);
            }
        }
        if ($fileUrl && $fileExist) {
            return ['code' => 1, 'msg' => '上传成功', 'data' => ['url' => $fileUrl]];
        }
        if ($uploadType != 'local') {
            $uploadConfig = sysconfig($uploadType);
        }


        $ext = $File->getOriginalExtension();
        $FilePath = $File->getRealPath();
        if (static::isPicture($ext) && $is_water) {
            //水印
            $waterConfig = sysconfig('watermark');
            if($waterConfig['switch']) {
                $image = Image::open($FilePath);
                try {
                    if ($waterConfig['type'] == 1&&$waterConfig['text']&&$waterConfig['font_size']&&$waterConfig['font_color']&&$waterConfig['position']) {
                            $font_path = ROOT_PATH . 'vendor/topthink/think-captcha/assets/zhttfs/1.ttf';
                            $res = $image->text($waterConfig['text'], $font_path, $waterConfig['font_size'], $waterConfig['font_color'], $waterConfig['position'])->save($FilePath);

                    } else if($waterConfig['img']&&$waterConfig['position']){

                        $res = $image->water(ROOT_PATH . '/public' . $waterConfig['img'], $waterConfig['position'])->save($FilePath);
                    }
                }catch (\Exception $e){
                    return ['code' => 0, 'msg' => $e->getMessage()];
                }
            }
        }

        if (static::isPicture($ext) && $thumb && is_numeric($thumb)) {
            $size = getimagesize($FilePath);
            if ($size[0] > $thumb || $size[1] > $thumb) {
                $image = Image::open($FilePath);
                $image->thumb($thumb, $thumb, 1)->save($FilePath);
            }
        }

        try {
            $upload = Uploadfile::instance()
                ->setUploadType($uploadType)
                ->setUploadConfig($uploadConfig)
                ->setFile($File)
                ->setHash($hash)
                ->save();
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
        if (@$upload['save'] == true) {
            $data=$upload['data'];
            $data['user_id']=cacheUserid();
            (new SystemUploadfile())->save($data);
            return ['code' => 1, 'msg' => '上传成功', 'data' => $data];
        } else {
            return ['code' => 0, 'msg' => $upload['msg']];
        }
    }

    public static function upBase64($base64)
    {
        $base64 = urldecode($base64);
        $md5 = md5($base64);
        $filemode = new SystemUploadfile();
        $n = $filemode->where('sha1', $md5)->find();
        if (empty($n)) {
            preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result);
            $type = $result[2];


            $uploadConfig = sysconfig('upload');

            $maxSize = $uploadConfig['upload_allow_size'] * 1024 * 1024;
            $allowExt = $uploadConfig['upload_allow_ext'];
//            $rule = [
//                'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$maxSize}",
//            ];

            $exts = explode(',', $allowExt);
            if (!in_array($type, $exts)) {
                return array('code' => 0, 'msg' => '上传的后缀不支持');
            }

            $name = md5(uniqid(microtime(true)) . create_random_str(10)) . '.' . $type;
            $dirstr = DS . 'uploads' . DS . date("Y") . DS . date("md") . DS;
            $savepath = ROOT_PATH . 'public' . DS . $dirstr;

            $tmpImage = base64_decode(str_replace($result[1], '', $base64));
            if (preg_match("/(POST|GET)/is", $tmpImage)) {
                return array('code' => -1, 'msg' => '图片有问题');
            }
            dir_create($savepath);
            file_put_contents($savepath . $name, $tmpImage);
            if (!is_file($savepath . $name)) {
                return array('code' => 0, 'msg' => '存储失败');
            }
            $path = str_replace("\\", "/", $dirstr);
            $realpath = $path . $name;
            $data['sha1'] = $md5;
            $data['user_id'] = cacheUserid();
            $data['upload_type'] = 'local';
            $data['original_name'] = $name;
            $data['file_ext'] = $type;
            $data['file_size'] = filesize($savepath . $name);
            $data['url'] = $realpath;
            $filemode->save($data);
            return array('code' => 1, 'msg' => '上传成功', 'data' => $data);
        } else {
            return array('code' => 1, 'msg' => '上传成功', 'data' => $n);
        }
    }

    public static function isPicture($ext)
    {
        if (in_array(strtolower($ext), array('ico', 'gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'))) {
            return true;
        }
        return false;
    }

    private static function checkHex($file)
    {
        $resource = fopen($file['tmp_name'], 'rb');
        $fileSize = filesize($file['tmp_name']);
        fseek($resource, 0);
        // 读取文件的头部和尾部
        if ($fileSize > 512) {
            $hexCode = bin2hex(fread($resource, 512));
            fseek($resource, $fileSize - 512);
            $hexCode .= bin2hex(fread($resource, 512));
        } // 读取文件的全部内容
        else {
            $hexCode = bin2hex(fread($resource, $fileSize));
        }
        fclose($resource);
        /* 匹配16进制中的 <% (  ) %> */
        /* 匹配16进制中的 <? (  ) ?> */
        /* 匹配16进制中的 <script  /script>  */
        if (preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054.*?2F5343524950543E)|(3C736372697074.*?2F7363726970743E)/is", $hexCode)) {
            return false;
        } else {
            return true;
        }
        return true;
    }
}